import tkinter as tk
from tkinter import messagebox
import json
import os
import sys

# 添加项目根目录到路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


def validate_hex_string(hex_str: str) -> bool:
    """验证十六进制字符串"""
    if not hex_str:
        return False
        
    # 移除空格和换行
    hex_str = hex_str.replace(' ', '').replace('\n', '').replace('\r', '')
    
    # 检查是否只包含十六进制字符
    try:
        int(hex_str, 16)
        return True
    except ValueError:
        return False


def format_hex_string(hex_str: str) -> str:
    """格式化十六进制字符串"""
    # 移除空格和换行
    hex_str = hex_str.replace(' ', '').replace('\n', '').replace('\r', '')
    
    # 每两个字符添加一个空格
    formatted = ' '.join([hex_str[i:i+2] for i in range(0, len(hex_str), 2)])
    
    return formatted.upper()


def copy_to_clipboard(text: str):
    """复制文本到剪贴板"""
    try:
        root = tk.Tk()
        root.withdraw()  # 隐藏窗口
        root.clipboard_clear()
        root.clipboard_append(text)
        root.update()  # 更新剪贴板
        root.destroy()
    except Exception as e:
        messagebox.showerror("错误", f"复制到剪贴板失败: {str(e)}")


def show_error_dialog(title: str, message: str):
    """显示错误对话框"""
    messagebox.showerror(title, message)


def show_warning_dialog(title: str, message: str):
    """显示警告对话框"""
    messagebox.showwarning(title, message)


def show_info_dialog(title: str, message: str):
    """显示信息对话框"""
    messagebox.showinfo(title, message)


def get_config_path(config_name: str) -> str:
    """获取配置文件路径"""
    config_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config')
    return os.path.join(config_dir, config_name)


def load_json_safe(file_path: str, default: dict = None) -> dict:
    """安全加载JSON文件"""
    try:
        if os.path.exists(file_path):
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        else:
            return default or {}
    except Exception as e:
        print(f"加载JSON文件失败: {file_path}, 错误: {str(e)}")
        return default or {}


def save_json_safe(file_path: str, data: dict) -> bool:
    """安全保存JSON文件"""
    try:
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存JSON文件失败: {file_path}, 错误: {str(e)}")
        return False


def format_json_display(data: dict) -> str:
    """格式化JSON显示"""
    try:
        return json.dumps(data, ensure_ascii=False, indent=2)
    except Exception as e:
        return f"JSON格式化失败: {str(e)}"


def parse_json_safe(json_str: str) -> dict:
    """安全解析JSON字符串"""
    try:
        return json.loads(json_str)
    except Exception as e:
        return {"error": f"JSON解析失败: {str(e)}"}


def get_supported_commands(profile: str) -> list:
    """获取支持的指令列表"""
    try:
        from version_manager import get_frame_cfg_path_for_cmd
        
        commands = []
        # 这里可以根据实际需要实现获取指令列表的逻辑
        # 暂时返回一些常见的指令
        common_commands = [
            '0x0100', '0x0102', '0x0104', '0x0107', '0x0108', '0x010e',
            '0x0200', '0x8100', '0x8103', '0x8104', '0x8105', '0x8106',
            '0x8107', '0x8108', '0x810e', '0x9003', '0x1003'
        ]
        
        # 验证每个指令是否在指定版本中可用
        for cmd in common_commands:
            try:
                get_frame_cfg_path_for_cmd(cmd, profile)
                commands.append(cmd)
            except:
                continue
                
        return commands
        
    except Exception as e:
        print(f"获取支持指令失败: {str(e)}")
        return []


def create_tooltip(widget, text: str):
    """创建工具提示"""
    def on_enter(event):
        tooltip = tk.Toplevel()
        tooltip.wm_overrideredirect(True)
        tooltip.wm_geometry(f"+{event.x_root+10}+{event.y_root+10}")
        
        label = tk.Label(tooltip, text=text, background="lightyellow", 
                        relief="solid", borderwidth=1, font=("Arial", 8))
        label.pack()
        
        widget.tooltip = tooltip
        
    def on_leave(event):
        if hasattr(widget, 'tooltip'):
            widget.tooltip.destroy()
            del widget.tooltip
            
    widget.bind("<Enter>", on_enter)
    widget.bind("<Leave>", on_leave)
